package com.foreknow.elm.dao.impl;

import com.foreknow.elm.dao.OrderdetailetDao;
import com.foreknow.elm.po.Orderdetailet;
import com.foreknow.elm.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class OrderdetailetDaoImpl implements OrderdetailetDao {
    private Connection con = null;
    private PreparedStatement pst = null;
    private ResultSet rs = null;
    @Override
    public int saveOrderdetailet(List<Orderdetailet> list) throws Exception {
        int result = 0;
        String sql = "insert into orderdetailet(orderId,foodId,quantity) values(?,?,?)";
        for (int i = 1; i < list.size(); i++) {
            sql.concat(",values(???)");
        }
        try {
            con = DBUtil.getConnection();
            pst = con.prepareStatement(sql);
            int count = 1;
            for (Orderdetailet orderdetailet : list){
                pst.setInt(count++, orderdetailet.getOrderId());
                pst.setInt(count++, orderdetailet.getFoodId());
                pst.setInt(count++, orderdetailet.getQuantity());
            }
            result = pst.executeUpdate();
        } finally {
            DBUtil.close(pst);
        }
        return result;
    }

    @Override
    public List<Orderdetailet> getOrderdetailet(int orderId) throws Exception {
        List<Orderdetailet> list = new ArrayList<>();
        String sql = "select * from orderdetailet where orderId = ?";
        try {
            con = DBUtil.getConnection();
            pst = con.prepareStatement(sql);
            pst.setInt(1, orderId);
            rs = pst.executeQuery();
            while (rs.next()){
                Orderdetailet orderdetailet = new Orderdetailet();
                orderdetailet.setOdId(rs.getInt("odId"));
                orderdetailet.setOrderId(rs.getInt("orderId"));
                orderdetailet.setFoodId(rs.getInt("foodId"));
                orderdetailet.setQuantity(rs.getInt("quantity"));
                list.add(orderdetailet);
            }
        } finally {
            DBUtil.close(rs,pst);
        }
        return list;
    }
}
